from django.shortcuts import render, redirect, reverse
from django.views.generic import View
# TODO: 增加一个debug和sql_queries变量。在模板中可以通过他来查看到一些数据库查询。
from django.template.context_processors import debug
# TODO: 增加一个request变量。这个request变量也就是在视图函数的第一个参数
from django.template.context_processors import request
# TODO: Django有内置的用户系统，这个上下文处理器会增加一个user对象
from django.contrib.auth.context_processors import auth
# TODO: messages：增加一个messages变量
from django.contrib import messages
from .forms import SignupForm, SigninForm
from .models import User


class IndexView(View):
    """首页视图"""

    def get(self, request, *args, **kwargs):
        users = User.objects.all()
        for user in users:
            print(user)
        return render(request, 'index.html')


class SignupView(View):
    """注册视图"""

    def get(self, request, *args, **kwargs):
        return render(request, 'signup.html')

    def post(self, request, *args, **kwargs):
        form = SignupForm(request.POST)
        if form.is_valid():
            # 表单验证成功提交数据
            form.save()
            # 重定向到首页
            return redirect(reverse('front:index'))
        else:
            errors = form.errors.get_json_data()
            print(errors)
            # 验证失败重定向到当前页面
            return redirect(reverse('front:signup'))


class SigninView(View):
    """登录"""

    def get(self, request, *args, **kwargs):
        return render(request, 'signin.html')

    def post(self, request, *args, **kwargs):
        form = SigninForm(request.POST)
        if form.is_valid():
            telphone = form.cleaned_data.get('telphone')
            password = form.cleaned_data.get('password')
            user = User.objects.filter(telphone=telphone, password=password).first()
            if user:
                # TODO: 登录成功session设置当前登录人ID，有效时间24小时
                request.session['user_id'] = user.id
                request.session.set_expiry(86400)
                # TODO: 登录成功重定向到首页
                return redirect(reverse('front:index'))
            else:
                # 验证失败重定向到当前页面
                # messages.add_message(request, level='info', message='手机号或密码不正确')
                messages.info(request, message='手机号或密码不正确')
                return redirect(reverse('front:signin'))
        else:
            # errors = form.errors.get_json_data()
            errors = form.get_form_error()
            for error in errors:
                messages.info(request, message=error)
            # 验证失败重定向到当前页面
            return redirect(reverse('front:signin'))


class BlogView(View):
    """博客"""

    def get(self, request, *args, **kwargs):
        return render(request, 'blog.html')


class VideoView(View):
    """视频"""

    def get(self, request, *args, **kwargs):
        return render(request, 'video.html')
